<template>
  <a-spin :spinning="confirmLoading">
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <!-- 基础信息区域：一行3列布局 -->
       <!--  <a-row>
          <a-col :span="8">
            <a-form-item label="联系人" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.contact" :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.phone" :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="电子邮件" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
              <a-input placeholder="请输入" v-model="model.email" :disabled="disabled" />
            </a-form-item>
          </a-col>
        </a-row> -->
        <a-row>
          <!-- 编码 -->
          <a-col :span="8">
            <a-form-model-item label="编码" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="code">
              <a-input v-model="model.code" placeholder="请输入" @blur="onCodeNameBlur" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <!-- 名称 -->
          <a-col :span="8">
            <a-form-model-item label="名称" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="name">
              <a-input v-model="model.name" placeholder="请输入" @blur="onCodeNameBlur" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <!-- 助记名 -->
          <a-col :span="8">
            <a-form-model-item label="助记名" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="auxName">
              <a-input v-model="model.auxName" placeholder="请输入" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <!-- 供应商分类 -->
          <a-col :span="8">
            <a-form-model-item label="供应商分类" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="supplierCategory">
              <j-dict-select-tag v-model="model.supplierCategory" dictCode="x_supplierr_category" placeholder="请选择"
                :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <!-- 供应商等级 -->
          <a-col :span="8">
            <a-form-model-item label="供应商等级" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="supplierLevel">
              <j-dict-select-tag v-model="model.supplierLevel" dictCode="x_supplier_level" placeholder="请选择"
                :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <!-- 纳税规模 -->
          <a-col :span="8">
            <a-form-model-item label="纳税规模" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="taxScale">
              <j-dict-select-tag v-model="model.taxScale" dictCode="x_tax_scale" placeholder="请选择"
                :disabled="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <!-- 备选供应商 -->
          <a-col :span="8">
            <a-form-model-item label="备选供应商" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="alterSuppliers">
              <a-input v-model="model.alterSuppliers" placeholder="请输入" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <!-- 启用 -->
          <a-col :span="8">
            <a-form-model-item label="启用" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="isEnabled">
              <j-dict-select-tag v-model="model.isEnabled" dictCode="yn" placeholder="请选择" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="remark">
              <a-textarea v-model="model.remark" :disabled="disabled" rows="1" autoSize placeholder="请输入" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <!-- 备注（textarea跨3列，避免输入框过窄） -->
               <!-- 子表单区域 -->
        <a-tabs v-model="activeKey" @change="handleChangeTabs">
          <a-tab-pane tab="产品" :key="refKeys[0]" :forceRender="true">
            <j-vxe-table keep-source :ref="refKeys[0]"  :columns="entryTable.columns"
              :dataSource="entryTable.dataSource" :maxHeight="300" :disabled="disabled" :rowNumber="false"
              :rowSelection="!disabled" :toolbar="!disabled" :resizable="true"
              :edit-config="{ trigger: 'click', mode: 'row', showIcon: false }"
              @edit-actived="({ row }) => setProductUnitOptions(row, $refs.entryTable)" @added="onInEntryAdded"
              @valueChange="onEntryValueChange" />
          </a-tab-pane>
        </a-tabs>
        </a-row>

        <!-- 折叠面板区域：内部保持一行3列布局 -->
        <a-collapse v-model:activeKey="collapseActiveKey" :bordered="false" class="custom-collapse">
          <!-- 开票信息 -->
          <a-collapse-panel key="1" header="开票信息" :style="collapseStyle">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="单位名称" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoiceCompany">
                  <a-input v-model="model.invoiceCompany" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="税号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoiceTaxCode">
                  <a-input v-model="model.invoiceTaxCode" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开户行" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoiceBankName">
                  <a-input v-model="model.invoiceBankName" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="行号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoiceBankCode">
                  <a-input v-model="model.invoiceBankCode" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="账号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoiceAccount">
                  <a-input v-model="model.invoiceAccount" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="invoicePhone">
                  <a-input v-model="model.invoicePhone" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <!-- 开票地址：跨3列，地址输入需较长宽度 -->
              <a-col :span="24">
                <a-form-model-item label="开票地址" :labelCol="labelCol1" :wrapperCol="wrapperCol16" prop="invoiceAddress">
                  <a-input v-model="model.invoiceAddress" placeholder="请输入详细地址" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <!-- 办款资料 -->
          <a-collapse-panel key="2" header="办款资料" :style="collapseStyle">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="单位名称" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="receiptCompany">
                  <a-input v-model="model.receiptCompany" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开户行" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="receiptBankName">
                  <a-input v-model="model.receiptBankName" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="行号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="receiptBankCode">
                  <a-input v-model="model.receiptBankCode" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <!-- 账号：跨3列，账号可能需复制，宽度充足更友好 -->
              <a-col :span="24">
                <a-form-model-item label="账号" :labelCol="labelCol1" :wrapperCol="wrapperCol16" prop="receiptAccount">
                  <a-input v-model="model.receiptAccount" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>

          <!-- 收件信息 -->
          <a-collapse-panel key="3" header="收件信息" :style="collapseStyle" class="custom-collapse-panel">
            <div class="collapse-content">
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="收件人" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="recvName">
                    <a-input v-model="model.recvName" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="recvPhone">
                    <a-input v-model="model.recvPhone" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="传真" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="recvFax">
                    <a-input v-model="model.recvFax" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-model-item label="Email" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="recvEmail">
                    <a-input v-model="model.recvEmail" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="邮编" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="recvPostcode">
                    <a-input v-model="model.recvPostcode" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="地址" :labelCol="labelCol1" :wrapperCol="wrapperCol16" prop="recvAddress">
                    <a-input v-model="model.recvAddress" placeholder="请输入详细地址" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </div>
          </a-collapse-panel>

          <!-- 财务信息 -->
          <a-collapse-panel key="4" header="财务信息" :style="collapseStyle" class="custom-collapse-panel">
            <div class="collapse-content">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="财务联系人" :labelCol="labelCol3" :wrapperCol="wrapperCol3"
                    prop="financialContacts">
                    <a-input v-model="model.financialContacts" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="联系电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="financialPhone">
                    <a-input v-model="model.financialPhone" placeholder="请输入" :disabled="disabled" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </div>
          </a-collapse-panel>

          <!-- 其他信息 -->
          <a-collapse-panel key="9" header="其他信息" :style="collapseStyle">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="简称" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="shortName">
                  <a-input v-model="model.shortName" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="辅助名称" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="auxName">
                  <a-input v-model="model.auxName" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="供应商网站" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="website">
                  <a-input v-model="model.website" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="法人代表" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="legalPerson">
                  <a-input v-model="model.legalPerson" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="法人电话" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="legalPersonPhone">
                  <a-input v-model="model.legalPersonPhone" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属总公司" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="headquarters">
                  <a-input v-model="model.headquarters" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="业务区域" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="bizArea">
                  <j-area-linkage type="cascader" v-model="model.bizArea" placeholder="请选择" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所属地区" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="area">
                  <j-area-linkage type="cascader" v-model="model.area" placeholder="请选择" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="附件" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="attachment">
                  <j-upload v-model="model.attachment" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="供应商地址" :labelCol="labelCol1" :wrapperCol="wrapperCol16" prop="address">
                  <a-input v-model="model.address" placeholder="请输入" :disabled="disabled" />
                </a-form-model-item>
              </a-col>
              
            </a-row>
          </a-collapse-panel>

          <!-- 操作信息 -->
          <a-collapse-panel key="0" header="操作信息" :style="collapseStyle">
            <a-row>
              <a-col :span="8">
                <a-form-model-item label="创建时间" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="createTime">
                  <j-date v-model="model.createTime" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="创建人" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="createBy">
                  <j-dict-select-tag v-model="model.createBy" dictCode="sys_user,realname,username" :disabled="true" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="修改时间" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="updateTime">
                  <j-date v-model="model.updateTime" :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              
              <a-col :span="8">
                <a-form-model-item label="修改人" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="updateBy">
                  <j-dict-select-tag v-model="model.updateBy" dictCode="sys_user,realname,username" :disabled="true" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </div>
  </a-spin>
</template>

<script>
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
// import { FormMixin } from '../../common/mixins/FormMixin'
import { OrderVxeTableMixin } from '../../common/mixins/OrderVxeTableMixin'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
export default {
  name: 'BasSupplierForm',
  mixins: [ OrderFormGridMixin,OrderFormMixin,OrderVxeTableMixin,JVxeTableModelMixin],

  data() {
    return {
      model: {
        code: '',
        name: '',
        auxName: '',
        isEnabled: 1,
      },
      refKeys: ['entryTable',],
      tableKeys: ['entryTable',],
      activeKey: 'entryTable',

      // 明细
      entryTable: {
        loading: false,
        dataSource: [],
        url: {
          list: '/base/basSupplier/queryById'
        },
        columns: [
          {
            title: '产品',
            key: 'productId',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_product,name,id",
            width: "300px",
            fixed: 'left',
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '单价',
            key: 'amount',
            type: JVXETypes.inputNumber,
            width: "300px",
            align: "left",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
            // statistics: ['sum'],
          },
          {
            title: '币种',
            key: 'currency',
            type: JVXETypes.selectSearch,
            options: [],
            dictCode: "bas_currency,name,code",
            width: "300px",
            fixed: 'left',
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
        ]
      },
      validatorRules: {
        code: [
          { required: true, message: '请输入编码!' },
          { validator: (rule, value, callback) => validateDuplicateValue('bas_supplier', 'code', value, this.model.id, callback) }
        ],
        name: [
          { required: true, message: '请输入名称!' },
          { validator: (rule, value, callback) => validateDuplicateValue('bas_supplier', 'name', value, this.model.id, callback) }
        ],
        auxName: [
          { required: true, message: '请输入助记名!' },
          { validator: (rule, value, callback) => validateDuplicateValue('bas_supplier', 'aux_name', value, this.model.id, callback) }
        ],
        isEnabled: [{ required: true, message: '请选择是否启用!' },],
        creditQuota: [{ pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' },],
        recvEmail: [{ pattern: /^([\w]+\.*)([\w]+)@[\w]+\.\w{3}(\.\w{2}|)$/, message: '请输入正确的电子邮件!' },],
        recvPostcode: [{ pattern: /^[1-9]\d{5}$/, message: '请输入正确的邮政编码!' },],
      },
      url: {
        add: "/base/basSupplier/add",
        edit: "/base/basSupplier/edit",
        queryById: "/base/basSupplier/queryById"
      }
    }
  },
  created() {
    // 等待物料options加载完成
    this.initProductRelated();
  },
   methods: {
    addBefore() {
      this.entryTable.dataSource = [];
    },

    addAfter() {
      this.$refs.billHeader.fillBillNo(
        'stk_qtrk_bill_no',
        (billNo) => {
          this.$nextTick(() => {
            //异步执行原因，初始空白行增加时，billNo可能还未获得！
            let rows = this.$refs.entryTable.getNewDataWithId();
            for (let row of rows) {
              this.$refs.entryTable.setValues([{ rowKey: row.id, values: { batchNo: billNo + '-' + row.entryNo } }]);
            }
          })
        });
    },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    editAfter() {  
      setTimeout(() => {
       if (this.model.id) {
        let params = { id: this.model.id };
        this.requestSubTableData(this.entryTable.url.list, params, this.entryTable,'productList', () => {
          console.log('产品明细数据加载结果：', this.entryTable.dataSource); // 新增日志
          // 检查明细数据是否为空
          if (!this.entryTable.dataSource || this.entryTable.dataSource.length === 0) {
            console.warn('明细数据为空，可能接口返回空或参数错误');
          }
        });
      }
      }, 500);
      
    },

    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        productList: allValues.tablesValue[0].tableData,
      }
    },

    onEntryValueChange(event) {
      const { type, value, oldValue, row, column, target, isSetValues } = event;
      if (value === oldValue || isSetValues) return;

      switch (column.property) {
        case "entryNo": //联动：分录号 --> 批次
          if (!row.batchNo || row.batchNo === this.model.billNo + "-" + oldValue) {
            target.setValues([{ rowKey: row.id, values: { batchNo: this.model.billNo + "-" + value } }]);
          }
          break;
        case "materialId":
          this.handleMaterialChange(row, target);
          break;
        case "unitId":
          if (!oldValue || oldValue.length === 0 || !value || value.length === 0) break;
          let rate = this.getUnitRate(row.materialId, oldValue, value);
          if (!rate)
            target.setValues([{ rowKey: row.id, values: { unitId: oldValue } }]);
          else
            target.setValues([{
              rowKey: row.id,
              values: {
                qty: (row.qty * rate).toFixed(3),
                price: (row.price / rate).toFixed(2)
              }
            }]);
          break;
        case "qty":
        case "price":
          target.setValues([{
            rowKey: row.id,
            values: { cost: (row.qty * row.price).toFixed(2) }
          }]);
          break;
      }
    },

    costValidator({ cellValue, row, column }, callback, target) {
      const v = Number(cellValue);
      if (isNaN(v)) {
        callback();
        return;
      }

      let diff = v - Number((row.qty * row.price).toFixed(2));
      if (diff < -0.01001 || diff > 0.01001) {
        callback(false, '${title}的输入值与计算值相差超过0.01元！');
      } else {
        callback(true); //true：通过验证
      }
    },

  }
}
</script>

<style lang="less" scoped>
@import "../../common/less/BillForm.less";
</style>
